package com.zhudeshuai.zhudemolist.util;

import android.media.MediaRecorder;

import java.io.File;
import java.io.IOException;

/**
 * @author zhudeshuai
 * @since 2018/7/16
 */

public class AudioRecordUtil {

	private static MediaRecorder mMediaRecorder;

	/**
	 * 开始录音
	 *
	 * @param file 录音保存文件（包含文件名）
	 */
	public static void start(File file) {
		if (mMediaRecorder == null) {
			mMediaRecorder = new MediaRecorder();
			//配置mMediaRecorder相应参数
			//从麦克风采集声音数据
			mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			//设置保存文件格式为MP4
			mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
			//设置采样频率,44100是所有安卓设备都支持的频率,频率越高，音质越好，当然文件越大
			mMediaRecorder.setAudioSamplingRate(44100);
			//设置声音数据编码格式,音频通用格式是AAC
			mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
			//设置编码频率
			mMediaRecorder.setAudioEncodingBitRate(96000);
		}
		try {
			file.getParentFile().mkdirs();
			file.createNewFile();
			//设置录音保存的文件
			mMediaRecorder.setOutputFile(file.getAbsolutePath());
			//开始录音
			mMediaRecorder.prepare();
			mMediaRecorder.start();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	/**
	 * 停止录音
	 */
	public static void stop() {
		if (mMediaRecorder != null) {
			mMediaRecorder.stop();
			mMediaRecorder.release();
			mMediaRecorder = null;
		}
	}
}
